// 自动添加复制按钮
const addCopyButtons = () => {
    document.querySelectorAll('.code-block').forEach(pre => {
        if (!pre.querySelector('.copy-btn')) {
            const btn = document.createElement('button');
            btn.className = 'copy-btn';
            btn.textContent = '复制';
            pre.prepend(btn);
        }
    });
};
// 初始化事件绑定
const bindCopyEvents = () => {
    document.querySelectorAll('.code-block .copy-btn').forEach(btn => {
        if (!btn._bound) {
            btn._bound = true;
            btn.onclick = async (e) => {
                const codeBlock = e.target.closest('.code-block');
                if (!codeBlock) return;
                try {
                    // 确保权限
                    const permission = await navigator.permissions.query({name: 'clipboard-write'});
                    if (permission.state === 'granted' || permission.state === 'prompt') {
                        // 精确获取代码内容
                        const code = codeBlock.querySelector('code').innerText;
                        await navigator.clipboard.writeText(code);
                        // 视觉反馈
                        e.target.classList.add('copied-feedback');
                        setTimeout(() => {
                            e.target.classList.remove('copied-feedback');
                        }, 1000);
                    }
                } catch (error) {
                    console.error('复制失败:', error);
                    // 降级方案
                    const textarea = document.createElement('textarea');
                    textarea.value = codeBlock.querySelector('code').innerText;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                }
            };
        }
    });
};

// 增强的观察器配置
const observer = new MutationObserver((mutations) => {
    addCopyButtons();
    bindCopyEvents();
});
// 确保content元素存在
const contentDiv = document.getElementById('content');
if (contentDiv) {
    observer.observe(contentDiv, {
        childList: true,
        subtree: true,
        // 监听属性变化
        attributes: true,
        characterData: true
    });
}
// 延迟执行
setTimeout(() => {
    addCopyButtons();
    bindCopyEvents();
}, 100);